package com.hechi.demo.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hechi.demo.dto.ResultResponse;
import com.hechi.demo.entity.Doctor;
import com.hechi.demo.exception.TijianExceptionEnum;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //  System.out.println(request.getHeader("token"));
        System.out.println("into JWTInterceptor..................................");
        String token=request.getHeader("token");

        //那么我们就要把医生数据从token中提取出来？？？？？？？？？

        if(token!=null){
            System.out.println("开始解析token。。。。。。。。。。。。。。。");
            try{
                Claims claims= Jwts.parser().setSigningKey("123456---").parseClaimsJws(token).getBody();  //获取数据;

                Doctor doctor=new ObjectMapper().readValue((String)claims.get("currentdoctor"),Doctor.class);

                System.out.println("doctor:"+doctor.getDocCode()+","+doctor.getRealName());

                request.setAttribute("doctor",doctor);  // 这行代码表示拦截器解析token中的医生数据之后通过request传给后端接口


                //request.setAttribute("user",user);
            }catch (Exception e){
                //捕获过期异常
                e.printStackTrace();
                System.out.println("异常信息JWT拦截器输出："+e.getStackTrace());
                //返回一个json格式的ResultResponse
                ResultResponse resultResponse=new ResultResponse(TijianExceptionEnum.DOCTOR_LOGIN_TIMEOUT.getEnCode(),TijianExceptionEnum.DOCTOR_LOGIN_TIMEOUT.getEnMessage());

                //  response.getWriter().println(apiResponse.toJSONString());   // 这里就直接返回响应给前端
                try{
                    response.getWriter().println(resultResponse.toJSONString());  //
                }catch(Exception e2){

                }

                return false;

            }
        }

        return true;//true：放行  false：不放行
    }
}
